#include "game.h"
#include "matrix.h"
Game::Game()
{
  this->snake = new Snake;
  this->food = new Food;
  this->gameover=false;
}


void Game::run(direction dir)
{
  snake->dir = dir;
  snake->move();
  if(snake->x[0]==food->x && snake->y[0]==food->y)
  {
    score();
    food->none=true;
    snake->length++;
    bool suc = false;
    while(!suc)
    {
      suc = true;
      food->generate();
      for(int i=0;i<snake->length;i++)
      {
        if(food->x==snake->x[i]&&food->y==snake->y[i])
          suc = false;
      }
    }
    food->none=false;
    //      snake->move();
  }
  for(int i=1;i<snake->length;i++)
  {
    if(snake->x[0]==snake->x[i]&&snake->y[0]==snake->y[i])
    {
      snake->alive = false;        
    }
  }
  if(snake->alive)
  {
    update(); 
  }
  else
    this->gameover  = true;
}

void Game::update()
{
  clear();
  if(food->none==false)
  {
    setXY(food->x,food->y);
    delay(1);
    resetXY(food->x,food->y);
  } 
  for(int i=snake->length-1;i>=0;i--)
  {
    setXY(snake->x[i],snake->y[i]);
    delay(1);
    resetXY(snake->x[i],snake->y[i]);
  }
}

void Game::over()
{
  unsigned char i,j;
  for(i=0;i<80;i++)//输出一个频率的声音
  {
    digitalWrite(BEEP,HIGH);//发声音
    delay(1);//延时1ms
    digitalWrite(BEEP,LOW);//不发声音
    delay(1);//延时ms
  }

  for(i=0;i<100;i++)//输出另一个频率的声音,这里的100与前面的80一样，用来控制频率，可以自己调节
  {
    digitalWrite(BEEP,HIGH);
    delay(2);
    digitalWrite(BEEP,LOW);
    delay(2);
  }
}

void Game::restart()
{
  this->snake = new Snake;
  this->food = new Food;
  this->gameover=false;
}

void Game::score()
{
  unsigned char i,j;
  for(i=0;i<2;i++)//输出一个频率的声音
  {
    digitalWrite(BEEP,HIGH);//发声音
    delay(2);//延时1ms
    digitalWrite(BEEP,LOW);//不发声音
    delay(2);//延时ms
  }

  //  for(i=0;i<20;i++)//输出另一个频率的声音,这里的100与前面的80一样，用来控制频率，可以自己调节
  //  {
  //    digitalWrite(BEEP,HIGH);
  //    delay(1);
  //    digitalWrite(BEEP,LOW);
  //    delay(1);
  //  } 
}




